﻿using B.W.passport.EnitiyFrameWorkCore;
using B.W.passport.IBaseRepisitory;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace B.W.passport.BaseRepisitory
{
    public class BaseRepisitory<T>:IBaseRepisitory<T>where T : class   
    {         
        /// <summary>
        /// 数据库上下文
        /// </summary>
        private readonly PassportDbcontext db;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db"></param>
        public BaseRepisitory(PassportDbcontext db)
        {
            this.db = db;
        }

        /// <summary>
        /// 查询全部
        /// </summary>
        /// <returns></returns>
       public virtual IQueryable<T> GetAll()
       {
            return db.Set<T>().AsQueryable();
       }

        /// <summary>
        /// 根据条件查询
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public IQueryable<T>Find(Expression<Func<T, bool>> predicate)
        {
            return db.Set<T>().Where(predicate);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> AddAsync(T entity)
        {
            await db.Set<T>().AddAsync(entity);
            return await db.SaveChangesAsync();
        }


     
        /// <summary>
        /// 根据单个实体删除
        /// </summary>
        /// <param name="entity">要删除的实体</param>
        /// <returns>受影响的行数</returns>
        public virtual async Task<int> DeleteAsync(T entity)
        {
           
            db.Set<T>().Update(entity);
            return await db.SaveChangesAsync();
        }

        ///// <summary>
        /////  删除
        ///// </summary>
        ///// <param name="entity"></param>
        ///// <returns></returns>
        //public  async Task<int> Update(T entity)
        //{
        //    db.Set<T>().Update(entity);
        //    return db.SaveChanges();
        //}

        public async Task<List<T>> GetAllAsync(Expression<Func<T, bool>> param)
        {
            return await db.Set<T>().Where(param).ToListAsync();
             
        }


        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> UpdateDataAsync(T entity)
        {
           
                db.Set<T>().Update(entity);
                return await db.SaveChangesAsync();
            
        }

    }
}